﻿using System;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Data.Linq.SqlClient;
using System.Data.Entity;
using System.Web;
using System.Web.Security;
using System.Web.Mvc;
using System.Web.Routing;
using EKAABSInformationManagement.Service;
using EKAABSInformationManagement.Models;
using EKAABSInformationManagement.Database;

namespace EKAABSInformationManagement.Controllers
{
    public class AssetController : Controller
    {
        public AssetService assetService { get; private set; }
        public string from { get; private set; }
        public IAsyncSendingmail asyncSendmail { get; private set; }
        protected override void Initialize(RequestContext requestContext)
        {
            if (System.Web.HttpContext.Current.User.IsInRole("admin") != true)
            {
                HttpException ex = new HttpException(401, "");
                requestContext.HttpContext.AddError(ex);
            }
            if (assetService == null) { assetService = new AssetService(); }
            this.from = string.IsNullOrEmpty(ConfigurationManager.AppSettings["userName"]) ? "" : ConfigurationManager.AppSettings["userName"];
            this.from = this.from.Contains("@wicresoft.com") ? this.from : string.Concat(this.from, "@wicresoft.com");
            if (asyncSendmail == null) { asyncSendmail = new asyncSendingmail(); }
            base.Initialize(requestContext);
        }
        public ActionResult Index()
        {
            List<asset> assets = assetService.getAllAsset();
            return View(assets);
        }
        public ActionResult assetHistory(string dateRange)
        {
            if (string.IsNullOrEmpty(dateRange) == false)
            {
                dateRange = dateRange.ToLower().Trim();
            }
            IDictionary<asset, IEnumerable<assetHistory>> histories = null;
            int pi = default(int);
            int ps = default(int);
            Int32.TryParse(System.Configuration.ConfigurationManager.AppSettings["pagesize"].ToString(), out ps);
            if (ps == 0) ps = 20;
            switch (dateRange)
            {
                case "lastmonth":
                    histories = assetService.getAssetHistoryByTimeAndPI(DateTime.Now.AddMonths(-1), ps, pi);
                    break;
                case "lastsixmonths":
                default:
                    histories = assetService.getAssetHistoryByTimeAndPI(DateTime.Now.AddMonths(-6), ps, pi);
                    break;
            }

            return View(histories);
        }
        [HttpGet]
        public ActionResult getAllUsers()
        {
            try
            {
                employeeService service = new employeeService();
                List<employee> employees = service.getAllEmployeesInBell();
                StringBuilder result = new StringBuilder();
                result.Append("{\"employees\":[");

                foreach (employee e in employees)
                {
                    result.Append("{");
                    result.AppendFormat("\"alias\":\"{0}\"", e.alias);
                    result.Append("},");
                }

                result.Remove(result.Length - 1, 1);
                result.Append("]}");
                return Content(result.ToString());
            }
            catch { return Content("error"); }
        }
        [HttpGet]
        public ActionResult getAssetTypes()
        {
            try
            {
                List<assetType> types = assetService.getAllAssetTypes();
                if (types.Count == 0) return Content("{\"status\":\"1\"}");
                StringBuilder result = new StringBuilder();
                result.Append("{\"status\":\"2\",\"types\":[");

                foreach (assetType a in types)
                {
                    result.Append("{");
                    result.AppendFormat("\"type\":\"{0}\",\"hasNIC\":\"{1}\"", a.assetType1, a.hasNIC);
                    result.Append("},");
                }

                result.Remove(result.Length - 1, 1);
                result.Append("]}");
                return Content(result.ToString());
            }
            catch { return Content("{\"status\":\"4\"}"); }
        }
        [HttpGet]
        public ActionResult getAllAssetInfo(string alias)
        {
            try
            {
                List<asset> assets = assetService.getAllAsset(alias);
                if (assets.Count == 0) return Content("{\"status\":\"4\"");
                StringBuilder result = new StringBuilder();
                result.Append("{\"status\":\"2\",\"assets\":[");
                foreach (asset a in assets)
                {
                    result.Append("{");
                    result.AppendFormat("\"ID\":\"{0}\"", a.assetID);
                    result.Append("},");
                }
                result.Remove(result.Length - 1, 1);
                result.Append("]}");
                return Content(result.ToString());
            }
            catch { return Content("{\"status\":\"4\""); }
        }
        [HttpGet]
        public ActionResult getAllAssetInfoByAssetID(string assetID)
        {
            try
            {
                assetInfo info = assetService.getAllAssetInfo(assetID);
                if (info == null) return Content("{\"status\":\"4\"");
                string status = string.Empty;
                string mac = info.MAC;
                string date = string.Empty;
                if (info.status.HasValue)
                {
                    status = Enum.GetName(typeof(EKAABSInformationManagement.Service.status), info.status);
                }
                else
                {
                    status = "暂无状态";
                }
                if (string.IsNullOrEmpty(mac)) mac = "暂无MAC";
                if (info.latestUpdateDate.HasValue)
                {
                    date = info.latestUpdateDate.Value.ToShortDateString();
                }
                else
                {
                    date = "暂无最近更新日期";
                }
                StringBuilder result = new StringBuilder();
                result.Append("{");
                result.AppendFormat("\"status\":\"2\",\"owner\":\"{0}\",\"MAC\":\"{1}\",\"nstatus\":\"{2}\",\"date\":\"{3}\",\"model\":\"{4}\",\"type\":\"{5}\",\"Sn\":\"{6}\",\"description\":\"{7}\",\"assetID\":\"{8}\"", info.owner, mac, status, date, info.model, info.type, info.Sn, info.description, info.assetID);
                result.Append("}");
                return Content(result.ToString());
            }
            catch { return Content("{\"status\":\"4\""); }
        }
        [HttpPost]
        public ActionResult submit(assetInfo a)
        {
            try
            {
                bool isAssetExists = default(bool);
                bool isMacExists = default(bool);
                assetService.insert(a, out isAssetExists);
                if (isAssetExists == false && (a.hasNIC.HasValue ? a.hasNIC.Value : false))
                {
                    assetService.insertRelatedNetwork(a.MAC, a.assetID, out isMacExists);
                }
                if (isAssetExists != false || isMacExists != false)
                {
                    return Json(new { status = 1 });
                }
                else
                {
                    if (!string.IsNullOrEmpty(a.owner))
                    {
                        asyncSendmail.ccRecipient = this.from;
                        asyncSendmail.recipient = Membership.GetUser(a.owner).Email;
                        asyncSendmail.mailBody = string.Concat("Hi ", a.owner, ",\r\n\r\n资产（资产编号：", a.assetID, "）于", DateTime.Now.ToString(), "起已挂在", a.owner, "的名下，详情如下：\r\n资产编号：", a.assetID, "\r\n资产类型：", a.type, "\r\n资产型号：", a.model, "\r\n资产描述：", a.description, "\r\n\r\n如有疑问，请回复该邮件或直接联系PA，谢谢。\r\n\r\nRegards\r\n  --");
                        asyncSendmail.mailSubject = "资产信息";
                        asyncSendmail.AsyncSendmail();
                    }
                    return Json(new { status = 2 });
                }
            }
            catch { return Json(new { status = 4 }); }
        }
        [HttpPost]
        public ActionResult update(assetInfo a)
        {
            try
            {
                string preOwner = string.Empty;
                assetService.update(a, out preOwner);
                string recipient_c = string.Empty;
                string recipient_p = string.Empty;
                if (!string.IsNullOrEmpty(a.owner))
                {
                    MembershipUser owner_c = Membership.GetUser(a.owner);
                    if (owner_c != null) recipient_c = owner_c.Email;
                }
                if (!string.IsNullOrEmpty(preOwner))
                {
                    MembershipUser owner_p = Membership.GetUser(preOwner);
                    if (owner_p != null) recipient_p = owner_p.Email;
                }
                if (!string.IsNullOrEmpty(recipient_c))
                {
                    asyncSendmail.recipient = recipient_c;
                    asyncSendmail.ccRecipient = this.from;
                    asyncSendmail.mailBody = string.Concat("Hi ", a.owner, ",\r\n\r\n资产（资产编号：", a.assetID, "）于", DateTime.Now.ToString(), "起已挂在您的名下，详情如下：\r\n资产编号：", a.assetID, "\r\n资产类型：", a.type, "\r\n资产型号：", a.model, "\r\n资产描述：", a.description, "\r\n\r\n如有疑问，请回复该邮件或直接联系PA，谢谢。\r\n\r\nRegards\r\n  --");
                    asyncSendmail.mailSubject = "资产信息";
                    asyncSendmail.AsyncSendmail();
                }
                if (!string.IsNullOrEmpty(recipient_p))
                {
                    asyncSendmail.recipient = recipient_p;
                    asyncSendmail.ccRecipient = this.from;
                    asyncSendmail.mailBody = string.Concat("Hi ", preOwner, ",\r\n\r\n资产（资产编号：", a.assetID, "）于", DateTime.Now.ToString(), "起已转移至 “", a.owner, "” 的名下，详情如下：\r\n资产编号：", a.assetID, "\r\n资产类型：", a.type, "\r\n资产型号：", a.model, "\r\n资产描述：", a.description, "\r\n\r\n如有疑问，请回复该邮件或直接联系PA，谢谢。\r\n\r\nRegards\r\n  --");
                    asyncSendmail.mailSubject = "资产信息";
                    asyncSendmail.AsyncSendmail();
                }
                return Json(new { status = 2 });
            }
            catch { return Json(new { status = 4 }); }
        }
        [HttpPost]
        public ActionResult updateOwner(string assetID, string owner)
        {
            try
            {
                string preOwner = string.Empty;
                asset a = assetService.updateOwner(assetID, owner, out preOwner);
                string recipient_c = string.Empty;
                string recipient_p = string.Empty;
                if (!string.IsNullOrEmpty(owner))
                {
                    MembershipUser owner_c = Membership.GetUser(owner);
                    if (owner_c != null) recipient_c = owner_c.Email;
                }
                if (!string.IsNullOrEmpty(preOwner))
                {
                    MembershipUser owner_p = Membership.GetUser(preOwner);
                    if (owner_p != null) recipient_p = owner_p.Email;
                }
                if (!string.IsNullOrEmpty(recipient_c))
                {
                    asyncSendmail.recipient = recipient_c;
                    asyncSendmail.ccRecipient = this.from;
                    asyncSendmail.mailBody = string.Concat("Hi ", a.belongto, ",\r\n\r\n资产（资产编号：", a.assetID, "）于", DateTime.Now.ToString(), "起已挂在您的名下，详情如下：\r\n资产编号：", a.assetID, "\r\n资产类型：", a.type, "\r\n资产型号：", a.model, "\r\n资产描述：", a.description, "\r\n\r\n如有疑问，请回复该邮件或直接联系PA，谢谢。\r\n\r\nRegards\r\n  --");
                    asyncSendmail.mailSubject = "您新增了一个资产";
                    asyncSendmail.AsyncSendmail();
                }
                if (!string.IsNullOrEmpty(recipient_p))
                {
                    asyncSendmail.recipient = recipient_p;
                    asyncSendmail.ccRecipient = this.from;
                    asyncSendmail.mailBody = string.Concat("Hi ", preOwner, ",\r\n\r\n资产（资产编号：", a.assetID, "）于", DateTime.Now.ToString(), "起已转移至 “", a.belongto, "” 的名下，详情如下：\r\n资产编号：", a.assetID, "\r\n资产类型：", a.type, "\r\n资产型号：", a.model, "\r\n资产描述：", a.description, "\r\n\r\n如有疑问，请回复该邮件或直接联系PA，谢谢。\r\n\r\nRegards\r\n  --");
                    asyncSendmail.mailSubject = "资产转移信息";
                    asyncSendmail.AsyncSendmail();
                }
                return Json(new { status = 2 });
            }
            catch { return Json(new { status = 4 }); }
        }
        [HttpPost]
        public ActionResult delete(string ids)
        {
            try
            {
                string[] strs = ids.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                IList<assetInfo> infos = assetService.delete(strs);
                asyncSendmail.ccRecipient = this.from;
                asyncSendmail.mailSubject = "资产注销提醒";
                string user_c = string.Empty;
                foreach (assetInfo info in infos)
                {
                    if (!string.IsNullOrEmpty(user_c) && user_c != info.owner)
                    {
                        user_c = info.owner;
                        asyncSendmail.mailBody = string.Concat(asyncSendmail.mailBody, "\r\n\r\nRegards\r\n  --");
                        asyncSendmail.AsyncSendmail();
                        MembershipUser owner_c = Membership.GetUser(user_c);
                        if (owner_c != null) asyncSendmail.recipient = owner_c.Email;
                        asyncSendmail.mailBody = string.Concat("Hi ", user_c, ",\r\n\r\n你的下列资产已被注销，详情如下：\r\n\r\n资产编号：", info.assetID, "\r\n资产型号：", info.model, "\r\n资产类型：", info.type, "\r\n资产描述：", info.description);
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(user_c))
                        {
                            user_c = info.owner;
                            MembershipUser owner_c = Membership.GetUser(user_c);
                            if (owner_c != null) asyncSendmail.recipient = owner_c.Email;
                            asyncSendmail.mailBody = string.Concat("Hi ", user_c, ",\r\n\r\n你的下列资产已被注销，详情如下：\r\n\r\n资产编号：", info.assetID, "\r\n资产型号：", info.model, "\r\n资产类型：", info.type, "\r\n资产描述：", info.description);
                        }
                        else
                        {
                            asyncSendmail.mailBody = string.Concat(asyncSendmail.mailBody, "\r\n\r\n资产编号：", info.assetID, "\r\n资产型号：", info.model, "\r\n资产类型：", info.type, "\r\n资产描述：", info.description);
                        }
                    }
                }
                if (infos.Count > 0)
                {
                    asyncSendmail.mailBody = string.Concat(asyncSendmail.mailBody, "\r\n\r\nRegards\r\n  --");
                    asyncSendmail.AsyncSendmail();
                }
                return Json(new { status = 2 });
            }
            catch { return Json(new { status = 4 }); }
        }
        [HttpGet]
        public ActionResult getMACByAssetID(string assetID)
        {
            string MAC;
            try
            {
                MAC = assetService.getMACByAssetID(assetID);
                StringBuilder result = new StringBuilder();
                result.Append("{\"MAC\":[");
                result.Append("{");
                result.AppendFormat("\"MAC\":\"{0}\"", MAC);
                result.Append("}");
                result.Append("]}");
                return Content(result.ToString());
            }
            catch { return Content("error"); }
        }
    }
}
